package com.runa.rccprotocol.analysis.lichuang;

import com.runa.monitor.comm.dto.newComm.AffiliatePanelVO;
import com.runa.monitor.comm.dto.newComm.HotMeterVO;
import com.runa.monitor.comm.dto.newComm.PanelVO;
import com.runa.monitor.comm.dto.newComm.ValveVO;
import com.runa.persistence.RepositoryServicePersis;
import com.runa.protocol.analysis.MetaBufferAnalysis;
import com.runa.protocol.util.ByteUtil;
import com.runa.rccprotocol.dto.equdata.HeatMeterData;
import com.runa.rccprotocol.dto.equdata.TerminalCalendarClock;
import com.runa.rccprotocol.dto.equdata.ValveData;
import com.runa.rccprotocol.dto.runa.RunaConcenResponseData;
import lombok.extern.slf4j.Slf4j;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @author diandian
 * @Date 2022/4/26 14:16
 */
@Slf4j
public class LiChuangEquDataAnalysis extends MetaBufferAnalysis<byte[]> {

    private DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

    private String netEquNo;
    @Override
    public int fill(byte[] data, int length, String netEquNo) {
        this.netEquNo=netEquNo;
        int begin = -1;
        for (int i = 0; i < length; i++) {
            if (0x68 == (data[i] & 0xff)) {
                begin = i;
                break;
            }
        }
        if (begin == -1) {
            return 0;
        }
        //11字节到数据长度，2个字节位结尾的校验、结束字节
        if (length < begin + 11 + 2) {
            return -1;
        }

        int index = begin;
        //表设备
        ++index;
        boolean meterEqu = (data[index] & 0xff) == 0x20;
        boolean valveEqu = (data[index] & 0xff) == 0x50;
        //设备编号
        ++index;
        String equSerialNo = ByteUtil.byteToHexStringFlip(data, index, 4);
        index += 4;
        //厂商代码  其中 A5(59),A6(42)为厂商代码
        String factoryCode = ByteUtil.byteToHexString(data, index, 3);
        //力创厂家 005942(表)  005146(阀门)
        if (!"005942".equals(factoryCode) && !"005146".equals(factoryCode)) {
            return length - index;
        }

        index += 3;
        //控制码
        int ctr = data[index];
        ++index;
        //数据长度
        int dataLen = data[index] & 0xff;
        //判断报文是否完整，已16结尾
        byte end = data[index + dataLen + 2];
        if (0x16 != (end & 0xff)) {
            return length - end;
        }
        ++index;
        //校验判断
        byte sum = ByteUtil.sum(data, begin, dataLen + 11);
        if (sum != data[index + dataLen]) {
            return length - (begin + dataLen + 13);
        }

        //数据标识 901F
        if (!"901F".equals(ByteUtil.byteToHexString(data, index, 2))) {
            return length - (begin + dataLen + 13);
        }
        index += 2;
        //序列号
        byte s = data[index];
        ++index;

        if (meterEqu) {
            HotMeterVO meterData = new HotMeterVO();
            meterData.setMeterSerial(equSerialNo);
            handleMeterData(data, index, meterData);
        } else if (valveEqu) {
            ValveVO valveVO = new ValveVO();
//            ValveData valveData = new ValveData();
            valveVO.setValveSerial(equSerialNo);
            handleValveData(data, index, valveVO);
        }
        //11字节到数据长度，2个字节位结尾的校验、结束字节,dataLen数据包长度
//        return length - (begin + 11 + 2) - dataLen;
        return 0;
    }

    private void handleValveData(byte[] data, int index, ValveVO valveVO) {
        //以下解析 以数据为准

        //面板显示热量
        index++;
//        ByteUtil.bcd2str(data, index, 3, false);
        index += 3;
        //室内温度 以数据为准
        index++;
        float roomTem = Float.parseFloat((ByteUtil.bcd2str(data, index, 1, false)));
        index += 2;
        //设定温度 以数据为准
        index++;
//        ByteUtil.bcd2str(data, index, 2, false);
//        valveData.setTemperatureLockTarget(Float.parseFloat((ByteUtil.bcd2str(data, index, 1, false))));
        index += 2;
        //阀门开度 以数据为准
//        ByteUtil.bcd2str(data, index, 1, false);
        valveVO.setActOpen((float) ByteUtil.bcdToInt(data, index+1, 1, false));
        index += 1;
        //设定温度限值
        index++;
//        String s = ByteUtil.bcd2str(data, index, 2, false);
        valveVO.setTempUL((float) ByteUtil.bcdToInt(data, index+1, 1, false));
        index += 2;
        //温度修正限值
        index++;
//        ByteUtil.bcd2str(data, index, 2, false);
        valveVO.setTempDL((float) ByteUtil.bcdToInt(data, index+1, 1, false));
        index += 2;

        index += 2;

        //实时时间 格式???
        index++;
//        String equTime = ByteUtil.bcd2str(data, index, 6, false);
        index += 6;
//        try {
//            valveData.setDate(newComm SimpleDateFormat("yyMMddHHmmss").parse(equTime));
//        } catch (ParseException e) {
//            
//        }
        //用户状态ST 高字节：bit7-bit6:强制锁定，强制开10，强制关11
                //bit5: 1:欠费 bit4: 1: 检修  bit3：1电机故障  bit2:总线取电异常；bit1：法拉电容充电异常；bit0：电池电压异常；
                //与面板通讯状态：bit7：0正常 1故障
        String status = ByteUtil.bcd2str(data, index, 1, false);
        valveVO.setStatus(status);
        byte[] bits = ByteUtil.getBits(data[index]);
//        if (bits[7]==1) valveData.setFaults("电池电压异常");
//        if (bits[6]==1) valveData.setFaults("法拉电容充电异常");
//        if (bits[5]==1) valveData.setFaults("总线取电异常");
//        if (bits[4]==1) valveData.setFaults("电机故障");
//        if (bits[3]==1) valveData.setFaults("检修");
//        if (bits[2]==1) valveData.setFaults("欠费");
//        if (bits[1]==1) valveData.setFaults("强制关");
//        if (bits[0]==1) valveData.setFaults("故障");
        //通讯状态
//        index++;
        //阀门开度上限
//        index++;
        //阀门开度下限
//        index++;
        //保留
//        index+=10;
        //程序版本号
//        index++;
        //状态位
//        index++;
        //保留

//        index += 26;
//        byte datum = data[index];
//        int byBit = ByteUtil.getByBit(datum, 6);
        boolean valveState = bits[6] == 0;
//        valveData.setSwitchState(valveState);
        valveVO.setReadTime(new Date());

        short zero = 0;

        AffiliatePanelVO panel = new AffiliatePanelVO(0, 0, (float) roomTem, zero);
        panel.setReadTime(valveVO.getReadTime());
        panel.setSerial(valveVO.getValveSerial());
        //温度带面板使用map
//            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
//            stringObjectHashMap.put("valve",valveVO);
//            stringObjectHashMap.put("panel",panel);
        try {
            panel.setId(RepositoryServicePersis.getCommPanelByNetIdAndSerial(
                    RepositoryServicePersis.getCommNetEquipmentByNetSerial(this.netEquNo).getId(),valveVO.getValveSerial()).getId());
            valveVO.getPanelVOList().add(panel);
        }catch (Exception e){
            log.error("户阀挂面板无面板数据---valveData:{}",valveVO,e);
        }

        RunaConcenResponseData responseData = new RunaConcenResponseData();
        responseData.addRepData(valveVO);
        this.responseData = responseData;
    }

    private void handleMeterData(byte[] data, int index, HotMeterVO meterData) {
        //跳过单位
        ++index;
        //累热
        meterData.setAccHeat((float) (ByteUtil.bcdToInt(data, index, 4, false) * 0.01));
        index += 4;

        //冷量
        index += 5;

        //跳过单位
        ++index;
        //热功率
        meterData.setPower((float) (ByteUtil.bcdToInt(data, index, 4, false) * 0.01));
        index += 4;

        //跳过单位
        ++index;
        //瞬流
        meterData.setFlow((float) (ByteUtil.bcdToInt(data, index, 4, false) * 0.01));
        index += 4;

        //跳过单位
        ++index;
        //累流
        meterData.setAccFlow((float) (ByteUtil.bcdToInt(data, index, 4, false) * 0.01));
        index += 4;

        //供水温度
        meterData.setSupplyTemp((float) (ByteUtil.bcdToInt(data, index, 3, false) * 0.01));
        index += 3;

        //回水温度
        meterData.setReturnTemp((float) (ByteUtil.bcdToInt(data, index, 3, false) * 0.01));
        index += 3;

        //累计工作时间
        int workTime = ByteUtil.bcdToInt(data, index, 3, false);
        meterData.setWorkTime(workTime);
        index += 3;

        //设备时间
        String equTime = ByteUtil.byteToHexStringFlip(data, index, 7);
        try {
            Date parse = format.parse(equTime);
            meterData.setMeterDate(parse);
        } catch (ParseException e) {
            
        }
        index += 7;

        //状态
        index += 2;

        RunaConcenResponseData responseData = new RunaConcenResponseData();
        meterData.setReadDate(new Date());
        responseData.addRepData(meterData);
        this.responseData = responseData;
    }

    public static void main(String[] args) {
        String s="FEFE685003087336005146812E901F00010000000000000000000010003500000500FFFF3700000000002000801000000055555555555555648000C816";
        byte[] bytes = ByteUtil.hexStringToByte(s);
        LiChuangEquDataAnalysis liChuangEquDataAnalysis = new LiChuangEquDataAnalysis();
        int fill = liChuangEquDataAnalysis.fill(bytes, bytes.length,"");
    }

}
